﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ServerSocket
{

    class Program
    {
        private static byte[] result = new byte[1024];

        static Socket serverSocket;                         //创建Socket类型变量serverSocket，用于存储服务端的交互信息
        private static Socket clientSocket;                 //创建Socket类型变量clientSocke，用于存储客户端的交互信息
        private static Socket clientSocketA = null;         //创建Socket类型变量clientSocketA，用于实例化客户端
        private static Socket clientSocketB = null;         //创建Socket类型变量clientSocketB，用于实例化客户端

        static void Main(string[] args)
        {
            Program.SetPortFirst(8080);                         //设置第一个客户端的端口号
            Program.SetPortSecond(50000);                        //设置第二个客户端的端口号
        }

        //设置第一个客户端
        private static void SetPortFirst(int port)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");                                //设置ip地址
            serverSocket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);                                       //初始化socket
            serverSocket.Bind(new IPEndPoint(ip, port));                                //绑定ip，端口号
            serverSocket.Listen(10);                                                    //设置监听
            Console.WriteLine("监听{0}成功", serverSocket.LocalEndPoint.ToString());    //进入监听状态
            Thread myThread = new Thread(ListenClientConnect);                          //开启一个线程来监听客户端连接
            myThread.Start();                                                           //线程开启
            Console.ReadLine();

        }

        //设置第二个客户端
        private static void SetPortSecond(int port)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");                                //设置ip地址
            serverSocket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);                                       //初始化socket
            serverSocket.Bind(new IPEndPoint(ip, port));                                //绑定ip，端口号
            serverSocket.Listen(10);                                                    //设置监听
            Console.WriteLine("监听{0}成功", serverSocket.LocalEndPoint.ToString());    //进入监听状态
            Thread myThread = new Thread(ListenClientConnect);                          //开启一个线程来监听客户端连接
            myThread.Start();                                                           //线程开启
            Console.ReadLine();

        }

        // 监听客户端连接      
        private static void ListenClientConnect()
        {
            //持续监听客户端发来的信息
            while (true)
            {
                //Client连接上后 得到这个连接
                clientSocket = serverSocket.Accept();
                
                //如果clientSocketA为空，则说明并未实例化，所以值为clientSocket
                if (clientSocketA == null)
                {
                    clientSocketA = clientSocket;
                }
                //如果clientSocketB为空，则说明并未实例化，所以值为clientSocket
                else if (clientSocketB == null)
                {
                    clientSocketB = clientSocket;
                }
                else
                {
                    //当其中一个断开了，又重新连接时，需要再次保存连接
                    if (clientSocketB.IsBound)
                    {
                        clientSocketA = clientSocketB;
                        clientSocketB = clientSocket;
                    }
                    else
                    {
                        clientSocketB = clientSocketA;
                        clientSocketA = clientSocket;
                    }

                }
                //开个线程接收Client信息
                Thread receivedThread = new Thread(ReceiveMessage);
                //线程开启
                receivedThread.Start(clientSocket);

            }
        }

        //接收客户端传来的文本信息
        private static void ReceiveMessage(object clientSocket)
        {
            //创建Socket类型变量myClientSock，用于监听客户端
            Socket myClientSocket = (Socket)clientSocket;

            //持续监听
            while (true)
            {
                try
                {
                    //创建int类型变量revceiveNumber，用于监听客户端的数量
                    int revceiveNumber = myClientSocket.Receive(result);
                    Console.WriteLine(Encoding.ASCII.GetString(result, 0, revceiveNumber));
                    //当监听的客户端指定为第一个客户端时
                    if (myClientSocket == clientSocketA)
                    {
                        Console.WriteLine("从" + myClientSocket.RemoteEndPoint.ToString()+"那里接收");
                        if (clientSocketB != null && clientSocketB.IsBound)
                        {
                            Console.WriteLine(myClientSocket.RemoteEndPoint.ToString()+ "已经收到");
                            //获取第二个客户端发送的信息，然后发送到第一个客户端
                            clientSocketB.Send(result, 0, revceiveNumber, SocketFlags.None);
                        }
                        else
                        {
                            //给服务端发送提示发送失败的信息
                            myClientSocket.Send(Encoding.ASCII.GetBytes("另一个客户端未实例化! 发送失败!"));
                            Console.WriteLine("对方不在线上，发送失败！");
                        }
                    }
                    //当监听的客户端指定为第一个客户端时
                    else
                    {
                        Console.WriteLine("从" + myClientSocket.RemoteEndPoint.ToString()+"那里接收");
                        if (clientSocketA != null && clientSocketA.IsBound)
                        {
                            Console.WriteLine(myClientSocket.RemoteEndPoint.ToString() + " 已经接收");
                            //获取第二个客户端发送的信息，然后发送到第一个客户端
                            clientSocketA.Send(result, 0, revceiveNumber, SocketFlags.None);
                        }
                        else
                        {
                            //给服务端发送提示发送失败的信息
                            myClientSocket.Send(Encoding.ASCII.GetBytes("另一个客户端未实例化! 发送失败!"));
                            Console.WriteLine("对方不在线上，发送失败！");
                        }

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }
    }
}